package com.it.myreflect4;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;

public class MyReflectDemo {
    public static void main(String[] args) throws IllegalAccessException, IOException {
        /*
        对于任意一个对象，都可以把对象所有的字段名和值，保存到文件中去
         */
        //创建学生和老师的对象
        Student s = new Student("张三",23);
        Teacher t = new Teacher("波妞",34);
        getSaveObject(t);
    }

    private static void getSaveObject(Object obj) throws IllegalAccessException, IOException {
        //获取字节码对象
        Class clazz = obj.getClass();
        //创建IO流
        BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\java\\basic-code\\myreflect\\a.txt"));
        //获取所有的成员变量
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            //获取成员变量的名字
            String name = field.getName();
            //获取成员变量的值
            Object value = field.get(obj);
            bw.write(name+"="+value);
            bw.newLine();
        }
        bw.close();
    }
}
